SoundMgr = {};

local audioSoundDic = {};
local audioMusic = nil;
local audioClipDic = {};

function SoundMgr:play(sound, audio, volume, isMusic)
    if not volume then
        volume=1;
    end
    if isMusic and self:isCanPlayMusic(sound.name) then
        audio.clip = sound;
        audio:Play();
        self:setMusicVolume(volume);
        return ;
    end
    if not isMusic then
        audio.clip = sound;
        audio:Play();
        audio.volume = volume;
        return ;
    end
end

function SoundMgr:playMusic(soundName, volume)
    if audioClipDic[soundName] then
        self:play(audioClipDic[soundName], self:getAudioMusic(), volume, true);
    else
        ResMgr:getSound(soundName, function(sound)
            audioClipDic[soundName] = sound;
            self:playMusic(soundName, volume);
        end);
    end
end

function SoundMgr:playSound(soundName, volume)
    if audioClipDic[soundName] then
        self:play(audioClipDic[soundName], self:getAudioSound(), volume, false);
    else
        ResMgr:getSound(soundName, function(sound)
            audioClipDic[soundName] = sound;
            self:playSound(soundName, volume);
        end);
    end
end

function SoundMgr:clearSoundRes(soundName)
    audioClipDic[soundName] = nil;
    ResMgr:clearRes("Sound/" .. soundName);
end

function SoundMgr:getAudioMusic()
    if not audioMusic then
        audioMusic = UIRoot.gameObject:AddComponent(typeof(AudioSource));
        audioMusic.ignoreListenerVolume = true;
        audioMusic.volume = 1;
        audioMusic.loop = true;
    end
    return audioMusic;
end

function SoundMgr:setMusicVolume(volume)
    self:getAudioMusic().volume = volume;
end

function SoundMgr:getMusicVolume()
    return self:getAudioMusic().volume;
end

function SoundMgr:getAudioSound()
    local audioSound = nil;
    for i, v in ipairs(audioSoundDic) do
        if not v.isPlaying then
            audioSound = v;
            break;
        end
    end
    if not audioSound then
        audioSound = UIRoot.gameObject:AddComponent(typeof(AudioSource));
        table.insert(audioSoundDic, audioSound);
    end
    return audioSound;
end

function SoundMgr:setSoundTotalVolume(volume)
    AudioListener.volume = volume;
end

function SoundMgr:getSoundTotalVolume()
    return AudioListener.volume;
end

function SoundMgr:isCanPlayMusic(soundName)
    local audio = self:getAudioMusic();
    return not audio.isPlaying or audio.clip.name ~= soundName;
end

